import com.mysql.jdbc.Connection;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Connect_MySQL {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/logtxt";  // 一般默认3306，这里设置成6666  （33060）  MYSQL8  WMPNetworkSvc
    private static final String USER = "root";
    private static final String PASSWORD = "sa";
    private static Connection connection = null;

    static {
        //1、加载驱动程序（反射的方法）
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //2、连接数据库
        try {
            connection = (Connection) DriverManager.
                    getConnection(URL, USER, PASSWORD);//地址，用户名，密码
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        return connection;
    }
    public static void close() {
        try {
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static boolean insert(String logText, String time) {
        String sql = "insert into log (logtxt,timeStr) values(?,?)";

        java.sql.PreparedStatement ptmt = null;
        try {
            ptmt = getConnection().prepareStatement(sql);
        } catch (SQLException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            ptmt.setString(1, "["+logText+"],");
            ptmt.setString(2, time);
            ptmt.execute();//执行给定的SQL语句，该语句可能返回多个结果
            ptmt.close();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

    }
}
